// utils/db.js
const database = require("../databaseConfig/index");

// 通用封装：将 database.query 转为 Promise 风格
const query = (sql, params = [], conn = database) => {
  return new Promise((resolve, reject) => {
    conn.query(sql, params, (err, results) => {
      if (err) reject(err);
      else resolve(results);
    });
  });
};

// 封装事务处理函数
const withTransaction = async (taskFn) => {
  const conn = await new Promise((resolve, reject) => {
    database.getConnection((err, connection) => {
      if (err) return reject(err);
      resolve(connection);
    });
  });

  try {
    await query("START TRANSACTION", [], conn);
    const result = await taskFn(conn);
    await query("COMMIT", [], conn);
    conn.release();
    return result;
  } catch (error) {
    await query("ROLLBACK", [], conn);
    conn.release();
    throw error;
  }
};

module.exports = {
  query,
  withTransaction,
};
